<script setup>
import { userStore } from '@/stores/userStore'
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus'
import { UserFilled, User, Lock, Iphone, Message, Plus } from '@element-plus/icons-vue'
import http from '@/utils/http.js';

const uStore = userStore();
const loading = ref(false);
const registerUserForm = ref(null); // 表单引用

const registerUser = ref({
  userId: '',
  userNickname: '',
  userUsername: '',
  userPassword: '',
  rePassword: '',
  userPhone: '',
  userEmail: '',
  userAvatar: '',
})

const save = async () => {
  try {
    loading.value = true;
    await registerUserForm.value.validate();
    
    const res = await http.put('/users/update', registerUser.value)
    if (res.code === 666) {
      ElMessage.success('保存成功')
      uStore.updateUserInfo(res.data.userId)
    }
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    loading.value = false;
  }
}

// 密码一致性校验
const checkRePassword = (rule, value, callback) => {
  if (value !== registerUser.value.userPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 头像上传成功处理
const handleAvatarSuccess = (res) => {
  if (res.code === 666) {
    registerUser.value.userAvatar = res.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(res.msg || '头像上传失败')
  }
}
const clear =() =>{
    uStore.clearUserInfo()
  // 重置表单数据
  registerUser.value = {
    userId: '',
    userNickname: '',
    userUsername: '',
    userPassword: '',
    rePassword: '',
    userPhone: '',
    userEmail: '',
    userAvatar: ''
  }
}

const rules = {
  userNickname: [
    {required: true, message: '请输入昵称', trigger: 'blur'},
    {min: 1, max: 20, message: '长度为1 ~ 20位非空字符', trigger: 'blur'}
  ],
  userUsername: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 5, max: 16, message: '长度为5 ~ 16位非空字符', trigger: 'blur'}
  ],
  userPassword: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 5, max: 16, message: '长度为5 ~ 16位非空字符', trigger: 'blur'}
  ],
  rePassword: [
    {validator: checkRePassword, trigger: 'blur'}
  ],
  userPhone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur'}
  ],
  userEmail: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur'}
  ]
}

onMounted(() => {
  registerUser.value = {
    userId: uStore.userInfo.data.userId,
    userNickname: uStore.userInfo.data.userNickname,
    userUsername: uStore.userInfo.data.userUsername,
    userPassword: uStore.userInfo.data.userPassword,
    userPhone: uStore.userInfo.data.userPhone,
    userEmail: uStore.userInfo.data.userEmail,
    userAvatar: uStore.userInfo.data.userAvatar
  }
})
</script>

<template>
  <div class="user-edit-container">
    <h2 class="edit-title">编辑个人信息</h2>
    
    <el-form
      ref="registerUserForm"
      :model="registerUser" 
      :rules="rules"
      label-width="100px"
      class="user-edit-form"
      @keyup.enter="save"
    >
      <div class="form-content">
        <!-- 左侧表单 -->
        <div class="form-left">
          <el-form-item label="昵称" prop="userNickname">
            <el-input
              v-model="registerUser.userNickname"
              placeholder="请输入昵称"
              :prefix-icon="UserFilled"
            />
          </el-form-item>
          
          <el-form-item label="用户名" prop="userUsername">
            <el-input
              v-model="registerUser.userUsername"
              placeholder="请输入用户名"
              :prefix-icon="User"
            />
          </el-form-item>
          
          <el-form-item label="密码" prop="userPassword">
            <el-input
              v-model="registerUser.userPassword"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              type="password"
              show-password
            />
          </el-form-item>
          
          <el-form-item label="确认密码" prop="rePassword">
            <el-input
              v-model="registerUser.rePassword"
              placeholder="请再次输入密码"
              :prefix-icon="Lock"
              type="password"
              show-password
            />
          </el-form-item>
        </div>
        
        <!-- 右侧头像上传 -->
        <div class="form-right">
          <el-form-item label="头像" prop="userAvatar">
            <el-upload
              class="avatar-uploader"
              name="avatar"
              action="http://localhost:8080/users/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <div class="avatar-wrapper">
                <img v-if="registerUser.userAvatar" :src="registerUser.userAvatar" class="avatar">
                <div v-else class="avatar-placeholder">
                  <el-icon :size="40"><Plus /></el-icon>
                  <span>上传头像</span>
                </div>
              </div>
            </el-upload>
            <div class="avatar-tip">建议尺寸：200×200像素，支持JPG/PNG格式</div>
          </el-form-item>
          
          <el-form-item label="手机号" prop="userPhone">
            <el-input
              v-model="registerUser.userPhone"
              placeholder="请输入手机号"
              :prefix-icon="Iphone"
            />
          </el-form-item>
          
          <el-form-item label="邮箱" prop="userEmail">
            <el-input
              v-model="registerUser.userEmail"
              placeholder="请输入邮箱"
              :prefix-icon="Message"
            />
          </el-form-item>
        </div>
      </div>
      
      <el-form-item class="form-actions">
        <el-button 
          type="primary" 
          size="large"
          @click="save"
          :loading="loading"
        >
          保存修改
        </el-button>
        <el-button size="large" @click="clear">
          重置
        </el-button>
        <el-button class="custom-return-btn">  
            <RouterLink to="/user">返回首页</RouterLink>
        </el-button>      
    </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.custom-return-btn {
  background-color: #e6a23c; /* Element Plus warning 主色调 */
  color: white;
  border-radius: 30px;
  padding: 12px 24px;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.custom-return-btn:hover {
  background-color: #f0c14b;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.custom-return-btn a {
  color: white;
  text-decoration: none;
}

.custom-return-btn a:hover {
  color: #f0f0f0;
}
.user-edit-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.edit-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
}

.user-edit-form {
  margin-top: 20px;
}

.form-content {
  display: flex;
  gap: 40px;
}

.form-left {
  flex: 1;
}

.form-right {
  flex: 1;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-wrapper {
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.avatar-wrapper:hover {
  border-color: #409eff;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #8c939d;
}

.avatar-placeholder .el-icon {
  margin-bottom: 8px;
}

.avatar-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #999;
  text-align: center;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.el-form-item {
  margin-bottom: 22px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-content {
    flex-direction: column;
    gap: 20px;
  }
  
  .user-edit-container {
    padding: 20px;
  }
}
</style>